package com.itheima.springbootwebtlias.aspect;


import com.itheima.springbootwebtlias.mapper.EmpLoginLogMapper;
import com.itheima.springbootwebtlias.pojo.Emp;
import com.itheima.springbootwebtlias.pojo.EmpLoginLog;
import com.itheima.springbootwebtlias.pojo.Result;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;
import java.util.Map;

@Component
@Slf4j
@Aspect
public class EmpLoginLogAspect {

    @Autowired
    private EmpLoginLogMapper empLoginLogMapper;

    @Around("execution( * com.itheima.springbootwebtlias.controller.LoginController.login(..))")
    public Object empLoginLog(ProceedingJoinPoint pjp) throws Throwable {

        long start = System.currentTimeMillis();

        Result result = null;
        try {
            result = (Result) pjp.proceed();
        } finally {

            String token = "";

            if(result == null){
                result = Result.error("登录失败");
            }else {
                Map map = (Map) result.getData();
                token = (String) map.get("token");
            }

            long end = System.currentTimeMillis();
            Long a = end - start;

            Object[] args = pjp.getArgs();
//            Emp[] args = (Emp[]) pjp.getArgs();
            Emp arg = (Emp) args[0];
            String username = arg.getUsername();
            String password = arg.getPassword();

            int code = result.getCode();




            //1.定义登录日志对象，收集登录日志信息。
            EmpLoginLog empLoginLog = new EmpLoginLog();

            empLoginLog.setLoginTime(LocalDateTime.now());
            empLoginLog.setJwt(token);
            empLoginLog.setPassword(password);
            empLoginLog.setUsername(username);
            empLoginLog.setCostTime(a);
            empLoginLog.setIsSuccess((short) code);


            //2.调用登录日志的持久层接口，添加日志信息到登录日志表中
            empLoginLogMapper.insLog(empLoginLog);



        }

            return result;






    }

}
